package com.yuxer.mybatisplus.config;

import cn.hutool.core.util.RandomUtil;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.HashMap;
import java.util.Map;

/**
 * swagger设置
 *
 * @author 醋醋🐟
 * @since 2024/5/16 11:50
 */
@Configuration
public class SwaggerConfig implements WebMvcConfigurer {
    @Value("${spring.application.name:我的应用}")
    private String applicationName;

    /**
     * 根据@Tag 上的排序，写入x-order
     *
     * @return the global open api customizer
     */
    @Bean
    public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() {
        return openApi -> {
            if (openApi.getTags() != null) {
                openApi.getTags().forEach(tag -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("x-order", RandomUtil.randomInt(0, 100));
                    tag.setExtensions(map);
                });
            }
            if (openApi.getPaths() != null) {
                openApi.addExtension("x-test123", "333");
                openApi.getPaths().addExtension("x-abb", RandomUtil.randomInt(1, 100));
            }

        };
    }

    @Bean
    public OpenAPI customOpenApi() {
        return new OpenAPI()
                .info(new Info()
                        .title(this.applicationName)
                        .version("1.0")
                        .description("开发文档"));
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    }

    /**
     * 解决前端跨域访问问题
     * 还有一种解决方案是在每一个 controller 上加 @CrossOrigin
     *
     * @param registry 不知道
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //**匹配的是我们所有后台的路径，代表后台共享了什么资源
        registry.addMapping("/**")
                //匹配前台的服务器地址
//                .allowedOrigins("http://localhost:8080")
                .maxAge(300 * 1000)
                .allowedHeaders("*")
                //允许的前台的请求方式
                .allowedMethods("*");
    }
}